package com.lyb.spzx.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.lyb.common.utils.AuthContextUtil;
import com.lyb.spzx.manager.constant.CacheConstant;
import com.lyb.spzx.model.dto.system.system.SysUser;
import com.lyb.spzx.model.vo.common.Result;
import com.lyb.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求方式
        String method = request.getMethod();
        //如果是跨域。直接放行
        if ("OPTIONS".equals(method)){
            return true;
        }
        //获取token 没有就去登录
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)){
            responseNoLoginInfo(response);
            return false;
        }
        //如果token不为空，就验证token的合法性
        String redisToken = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_PREFIX + token);
        if (StrUtil.isEmpty(redisToken)){
            responseNoLoginInfo(response);
            return false;
        }
        //将用户信息存储到ThreadLocal中
        SysUser sysUser = JSON.parseObject(redisToken, SysUser.class);
        AuthContextUtil.set(sysUser);

        //重置Redis中用户数据的有效时间 TODO 上线前改回30分钟
        redisTemplate.expire(CacheConstant.USER_LOGIN_PREFIX+token ,300000, TimeUnit.MINUTES);
        //放行
        return true;
    }

    //返回数据给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");

        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null){
                writer.close();
            }
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除ThraedLocal中的数据
        AuthContextUtil.delete();
    }
}
